<template>
  <div ref="contentRef" class="markdown-viewer" v-html="renderedMarkdown"></div>
</template>

<script setup>
  import { ref, onMounted, computed } from "vue";
  import { ElMessage } from "element-plus";
  import { useClipboard } from "@vueuse/core";
  import MarkdownIt from "markdown-it";
  import texmath from "markdown-it-texmath";
  import katex from "katex";
  import hljs from "highlight.js";
  import "highlight.js/styles/vs2015.min.css";
  import "katex/dist/katex.min.css";
  import request from '../../request/axios';

  const props = defineProps({
    content: {
      type: String,
      required: true,
    },
  });

  const { copy } = useClipboard();
  const contentRef = ref();

  // 初始化 MarkdownIt 实例
  const md = new MarkdownIt({
    html: true, // 允许 HTML 标签
    linkify: true, // 自动将 URL 转换为链接
    typographer: true, // 启用排版优化（例如引号替换）
    breaks: true, // 将换行符转换为 <br>
    // 代码高亮
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          const highlightedCode = hljs.highlight(str, { language: lang }).value;
          const copyHtml = `<div class="copy-btn" data-copy="${encodeURIComponent(str)}">复制</div>`;
          const langLabel = `<span class="lang-label">${lang}</span>`;
          return `<pre class="hljs-pre"><code class="hljs ${lang}">${langLabel}${copyHtml}${highlightedCode}</code></pre>`;
        } catch (error) {
          console.log("Highlight error:", error);
        }
      }
      return `<pre><code>${md.utils.escapeHtml(str)}</code></pre`;
    },
  })
    // 添加数学公式支持
    .use(texmath, {
      engine: katex,
      delimiters: "dollars", // 支持 $...$ 和 $$...$$ 语法
      katexOptions: {
        throwOnError: false,
        strict: false,
      },
    });

  // 渲染 Markdown 内容
  const renderedMarkdown = computed(() => {
    // 预处理：支持多种数学公式语法
    let cleanedContent = (props.content || "")
      // 清理多余的反斜杠，例如 \\( a \\) 转换为 \( a \)
      .replace(/\\\\([()])/g, "\\$1")
      // 处理块级公式：\[...\] 转换为 $$...$$
      .replace(/\\\[\s*([\s\S]*?)\s*\\\]/g, (match, inner) => `$$${inner.trim()}$$`)
      // 处理内联公式：\(...\) 转换为 $...$
      .replace(/\\\(\s*([\s\S]*?)\s*\\\)/g, (match, inner) => `$${inner.trim()}$`)
      // 处理 [....] 转换为 $$...$$（如果用户直接用了 [...] 语法）
      .replace(/\[\s*([\s\S]*?)\s*\]/g, (match, inner) => `$$${inner.trim()}$$`)
      // 处理数据ivd展示数据
      .replace(/```ivd([\s\S]*?)```/g, '<span class="ivd-a">$1</span>')
      // 处理内联公式：$...$（避免误处理 $$...$$）
      .replace(/(?<!\$)\$\s*([^$]+?)\s*\$(?!\$)/g, (match, inner) => `$${inner.trim()}$`);

    try {
      // 先渲染 Markdown 内容
      let rendered = md.render(cleanedContent);

      // 后处理：清理渲染后文本中未被 katex 渲染的 $...$ 符号
      rendered = rendered.replace(/\$([^$]+?)\$/g, (match, inner) => {
        // 检查是否是数学公式内容（包含数学符号、字母、数字等）
        if (inner.match(/^[a-zA-Z0-9+\-*/=^_{}\\\s]+$/)) {
          // 如果是数学公式，尝试重新渲染
          try {
            return katex.renderToString(inner, { throwOnError: false, strict: false });
          } catch (e) {
            return inner; // 如果渲染失败，返回原始内容
          }
        }
        // 否则移除 $ 符号，仅保留内部内容
        return inner;
      });

      return rendered;
    } catch (error) {
      console.log("Markdown render error:", error);
      return cleanedContent;
    }
  });

  const ivdLinkUrl = async () => {
    try {
      const res = await request.getV2({ url: '/v1/api-jump' });
      if(res.code !== 200){
        ElMessage.error(res.msg)
        return
      }
      window.open(res.data.jump_url, '_blank');
    } catch (error) {
      console.log(error);
    }
  }

  // 挂载后添加复制按钮的事件监听
  onMounted(() => {
    contentRef.value.addEventListener("click", (e) => {
      if (e.target.classList.contains("copy-btn")) {
        const code = decodeURIComponent(e.target.dataset.copy);
        copy(code);
        ElMessage.success("复制成功!");
      }
    });

    contentRef.value.addEventListener("click", (e) => {
      if (e.target.classList.contains("ivd-a")) {
        ivdLinkUrl()
      }
    });
  });
</script>

<style lang="scss">
  .markdown-viewer {
    font-family: PingFang SC;
    font-size: 0.95rem;
    font-weight: 400;
    line-height: 1.6rem;
    letter-spacing: 0em;
    text-align: left;
    color: #3b3e55;
    max-width: 100%;

    .hljs-pre {
      position: relative;
      background: #1e1e1e;
      border-radius: 6px;
      padding: 10px;
      margin-bottom: 16px;
      overflow-x: auto;
    }

    .hljs {
      display: block;
      padding: 0.5em;
      color: #dcdcdc;
    }

    /* 语言标签 */
    .lang-label {
      position: absolute;
      top: 5px;
      left: 10px;
      font-size: 12px;
      color: #888;
      background: #2d2d2d;
      padding: 2px 6px;
      border-radius: 3px;
    }

    .copy-btn {
      position: absolute;
      top: 5px;
      right: 10px;
      font-size: 12px;
      color: #fff;
      background: #007acc;
      padding: 2px 8px;
      border-radius: 3px;
      cursor: pointer;
      user-select: none;

      &:hover {
        background: #005ea6;
      }
    }

    p {
      margin: 0;
      margin-bottom: 3px;
    }

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      color: var(--color-G900);
      margin: 24px 0 8px;
      font-weight: 600;
    }

    h1 {
      font-size: 22px;
      line-height: 32px;
    }

    h2 {
      font-size: 20px;
      line-height: 30px;
    }

    h3 {
      font-size: 18px;
      line-height: 28px;
    }

    h4 {
      font-size: 16px;
      line-height: 26px;
    }

    h5 {
      font-size: 16px;
      line-height: 24px;
    }

    h6 {
      font-size: 16px;
      line-height: 24px;
    }

    ul,
    ol {
      margin: 0 0 8px 0;
      padding: 0;
      font-size: 16px;
      line-height: 24px;
      color: #3b3e55;
    }

    li {
      margin: 4px 0 0 20px;
      margin-bottom: 1rem;
    }

    ol>li {
      list-style-type: decimal;
      margin-bottom: 1rem;
    }

    ul>li {
      list-style-type: disc;
      font-size: 16px;
      line-height: 24px;
      margin-right: 11px;
      margin-bottom: 1rem;
      color: #3b3e55;
    }

    ol ul,
    ol ul>li,
    ul ul,
    ul ul li {
      font-size: 16px;
      list-style: none;
      margin-left: 6px;
      margin-bottom: 1rem;
    }

    ul ul ul,
    ul ul ul li,
    ol ol,
    ol ol>li,
    ol ul ul,
    ol ul ul>li,
    ul ol,
    ul ol>li {
      list-style: square;
    }

    .katex {
      font-size: 1.1em;
    }

    .katex-display {
      margin: 1rem 0;
      text-align: center;
    }
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 1rem;
  }

  th,
  td {
    border: 1px solid #ccc;
    padding: 8px;
  }

  th {
    background-color: #e0e0e0;
    text-align: left;
    font-weight: 800;
    color: #333;
  }

  td {
    background-color: #f9f9f9;
    color: #3b3e55;
  }

  strong {
    font-weight: 900;
  }
   .ivd-a {
    cursor: pointer;
    color: #646CFF;
  }
</style>